<template>
  <!-- 农资投入管理 -->
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="26"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-cancel="false"
        :has-save="false"
        :has-edit-column="true"
        :has-export="true"
        @showColumn="showColumn"
        @download="download"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm
        :form-config="formConfig"
        :form-data="searchlist"
        @search="search"
      />
    </template>
    <template v-slot:table-box>
      <Table
        :key="itemKey"
        v-loading="loading"
        :prop-list="tableColumn"
        :list-data="tableData"
        @sortChange="changeTableSort"
        @handleSelectionChange="handleSelectionChange"
        :toolTip="false"
      >
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(26, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(26, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:facilityBOList="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeEquip(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <template v-slot:handlerName="{ row }">
          <template v-if="!row.index">
            <span v-if="row.personName">{{ row.personName }}</span>
            <span v-else>—</span>
          </template>
        </template>
        <template v-slot:assetQuantity="{ row }">
          <template v-if="!row.index">
            <div>{{ row.assetQuantity }}{{ row.unitName }}</div>
          </template>
        </template>
        <template v-slot:spec="{ row }">
          <template v-if="!row.index">
            <div>
              {{ row.materialDTO.specification }}
              {{ row.materialDTO.perSpecUnitName }}
              {{
                row.materialDTO.perSpecUnitName && row.materialDTO.unitName
                  ? "/"
                  : ""
              }}
              {{ row.materialDTO.unitName }}
            </div>
          </template>
        </template>
        <template v-slot:pictureNo="{ row, index }">
          <template v-if="!row.index">
            <div v-if="row.pictureNo" class="viewImgContainer">
              <div class="viewImg" @click="upimage(row.pictureNo, index)">
                <img
                  class="viewImg"
                  v-show="row.viewImg"
                  src="@/assets/unifiedPicture/viewImg1.png"
                />
              </div>
            </div>
            <el-button v-else type="text" disabled
              >{{ row.index }}暂无图片</el-button
            >
          </template>
        </template>
        <template v-slot:batchName="{ row, item }">
          <template v-if="!row.index">
            {{ row.productionBatchBO ? row.productionBatchBO[item.prop] : "" }}
          </template>
        </template>
        <template v-slot:materialName="{ row, item }">
          <template v-if="!row.index">
            {{ row.materialDTO ? row.materialDTO[item.prop] : "" }}
          </template>
        </template>
        <template v-slot:IdNameList="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeIdNameList(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '农资投入信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :rules="rules"
          :model="formData"
          class="el-form"
          :show-message="isshowmessage"
        >
          <el-form-item label="设施名称:" class="w50p" prop="facilityNoList">
            <el-select
              v-model="formData.facilityNoList"
              filterable
              clearable
              :disabled="nowChanceStau == 'add' ? false : true"
              @change="changeFacilityNo"
            >
              <el-option
                v-for="item in facilityAList"
                :key="item.facilityNo"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <!-- multiple
              :disabled="nowChanceStau == 'add' ? false : true"
              collapse-tags -->
          <el-form-item label="批次名称:" class="w50p" prop="batchNo">
            <el-select
              v-model="formData.batchNo"
              clearable
              filterable
              @change="getspecification"
            >
              <el-option
                v-for="item in batchAList"
                :key="item.batchNo"
                :label="item.batchName"
                :value="item.batchNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投入编号:" class="w50p">
            <el-select
              v-model="formData.batchSingleNos"
              placeholder="编号选择"
              clearable
              multiple
              filterable
            >
              <el-option
                v-for="(item, index) in singleNoList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投入农资:" class="w50p" prop="materialNo">
            <el-select
              v-model="formData.materialNo"
              filterable
              clearable
              @change="materialNoChange"
            >
              <el-option
                v-for="item in agriculturalMaterialList"
                :key="item.materialNo"
                :label="item.materialName"
                :value="item.materialNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="投入量:" class="w50p" prop="assetQuantity">
            <el-input
              style="width: 80%"
              v-model="formData.assetQuantity"
              type="number"
              min="0"
              clearable
              @input="numChange('assetQuantity')"
            />
            <div style="margin-left: 20px" v-if="formData.materialNo">
              {{
                agriculturalMaterialList.filter(
                  (el) => el.materialNo === formData.materialNo
                )[0].unitName
              }}
            </div>
          </el-form-item>
          <el-form-item label="换算量:" class="w50p">
            <el-input
              v-model="formData.exchangeRatio"
              style="width: 60%"
              type="text"
              placeholder="请输入换算量"
              clearable
            />
            <el-select
              v-model="formData.exchangeUnitNo"
              filterable
              style="width: 40%"
              clearable
            >
              <el-option
                v-for="item in unitlists"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="换算预览:" class="w50p" style="display: flex">
            <template
              v-if="
                formData.assetQuantity &&
                formData.exchangeRatio &&
                formData.materialNo &&
                formData.exchangeUnitNo
              "
            >
              <div>
                <span v-if="formData.assetQuantity && formData.exchangeRatio">{{
                  (formData.assetQuantity / formData.exchangeRatio).toFixed(2)
                }}</span>
                <span v-if="formData.materialNo">{{
                  agriculturalMaterialList.filter(
                    (el) => el.materialNo === formData.materialNo
                  )[0].unitName
                }}</span>
                <span v-if="formData.exchangeUnitNo"
                  >/{{
                    unitlists.filter(
                      (el) => el.unitNo === formData.exchangeUnitNo
                    )[0].unitName
                  }}</span
                >
              </div>
              <div style="margin-left: 10px">
                <span>总计</span>
                <span v-if="formData.exchangeRatio">{{
                  formData.exchangeRatio
                }}</span>
                <span v-if="formData.exchangeUnitNo">{{
                  unitlists.filter(
                    (el) => el.unitNo === formData.exchangeUnitNo
                  )[0].unitName
                }}</span>
              </div>
              <div style="margin-left: 10px">
                <span>总重</span>
                <span v-if="formData.assetQuantity">{{
                  formData.assetQuantity
                }}</span>
                <span v-if="formData.materialNo">{{
                  agriculturalMaterialList.filter(
                    (el) => el.materialNo === formData.materialNo
                  )[0].unitName
                }}</span>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="投入图片:" class="w50p">
            <ele-upload-image
              v-model="image"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :file-size="10"
              :action="ImageUrl()"
            />
          </el-form-item>
          <el-form-item label="经手人:" class="w50p" prop="personNo">
            <el-select v-model="formData.personNo" clearable>
              <el-option
                v-for="(item, index) in staffList"
                :key="index.personNo"
                :label="item.person.name"
                :value="item.personNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规格:" class="w50p">
            <el-input v-model="formData.spec" clearable disabled />
          </el-form-item>
          <el-form-item label="投入农资金额:" class="w50p" prop="assetValue">
            <el-input
              v-model="formData.assetValue"
              type="number"
              min="0"
              clearable
              @input="numChange('assetValue')"
            />
          </el-form-item>
          <el-form-item label="备注:" class="w50p" prop="remark">
            <el-input v-model="formData.remark" />
          </el-form-item>
          <el-form-item label="投入日期:" class="w50p" prop="assetDate">
            <el-date-picker
              v-model="formData.assetDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')"
            >取 消</el-button
          >
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
            >保 存</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        class="dialog"
        title="查看农资图片"
        @close="closeViewImg"
        :visible.sync="dialogFormPicVisible"
      >
        <img :src="imgUrl" />
        <!-- <div v-if="imgUrl">暂无图片</div> -->
      </el-dialog>

      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :table-column="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-one"
            @click="dialogTableColumnVisible = false"
          >
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveColumn">
            保 存
          </el-button>
        </div>
      </el-dialog>

      <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="facilityBOList"
        @closeDialog="isShowEquip = false"
      />

      <!-- 编号 -->
      <el-dialog
        title="单个编号"
        :visible.sync="showIdNameList"
        width="30%"
        class="dialogRec"
        @close="showIdNameList = false"
      >
        <div style="overflow: hidden;">
          <div v-for="(item, index) in singleNoList" :key="index" style="float: left;">
            <div
              v-if="!!activeSingleNoList"
              class="IdNameList"
              :class="
                activeSingleNoList.includes(item)
                  ? 'IdNameList activeId'
                  : 'IdNameList'
              "
            >
              {{ item }}
            </div>
            <div v-else class="IdNameList">{{ item }}</div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showIdNameList = false"
            >关 闭</el-button
          >
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import batcjreq from "@/api/digital-production/production-batch-manage/production-batch-query";
import SearchForm from "@/components/searchForm";
import Table from "@/components/table/table.vue";
import SeeEquip from "@/components/seeEquip/index.vue";
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import danwei from "@/api/basic-info-manage/unit-manage/index";
import nowpagereq from "@/api/basic-info-manage/agr-source-base-Manage/index";

import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
// test
import collectionPicture from "@/api/digital-production/collectionPicture/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
// import nowstaff from "@/api/digital-production/basic-info-manage/staff-manage";
import { mymixin } from "@/utils/mixin";
import userreq from "@/api/user/index";

import baseURL from "@/api/baseURL";
// import { getToken } from '@/utils/auth';
import { mapGetters } from "vuex";
export default {
  name: "AgrInputManagementtwo",
  components: {
    SearchForm,
    Table,
    ActionBar,
    Pagination,
    BaseMainSlot,
    SeeEquip,
  },
  mixins: [mymixin],
  data() {
    return {
      itemKey: '',
      showIdNameList: false,
      singleNoList: [],
      tableColumn: [
        {
          prop: "batchName",
          label: "批次名称",
          minWidth: "200",
          slotName: "batchName",
        },
        {
          prop: "batchNo",
          label: "批次号",
          minWidth: "200",
          slotName: "batchName",
        },
        {
          prop: "facilityBOList",
          label: "设施名称",
          minWidth: "120",
          slotName: "facilityBOList",
        },
        {
          prop: "IdNameList",
          label: "投入编号",
          slotName: "IdNameList",
          minWidth: "180",
        },
        {
          prop: "materialName",
          label: "投入农资名称",
          minWidth: "120",
          slotName: "materialName",
        },
        {
          prop: "handlerName",
          label: "经手人",
          width: "120",
          slotName: "handlerName",
        },
        {
          prop: "assetQuantity",
          label: "投入量",
          minWidth: "120",
          slotName: "assetQuantity",
        },
        // { prop: 'spec', label: '规格', minWidth: '120', slotName: 'spec' },
        {
          prop: "pictureNo",
          label: "农资图片",
          minWidth: "120",
          slotName: "pictureNo",
        },
        { prop: "assetDate", label: "投入日期", minWidth: "120" },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          width: "120",
        },
      ],
      formConfig: [
        {
          label: "批次名称",
          prop: "batchNo",
          type: "select",
          options: [], // batchList
          optionKey: { label: "batchName", value: "batchNo" },
        },
        {
          label: "设施名称",
          prop: "facilityNo",
          type: "select",
          options: [], // facilityList
          optionKey: { label: "facilityName", value: "facilityNo" },
        },
        {
          label: "农资名称",
          prop: "materialNo",
          type: "select",
          options: [], // queryagriculturalMaterialList
          optionKey: { label: "materialName", value: "materialNo" },
        },
        {
          label: "经手人",
          prop: "personNo",
          type: "select",
          options: [], // StaffList
          optionKey: { label: "personName", value: "personNo" },
        },
        {
          label: "选择时间",
          prop: "date",
          type: "daterange",
        },
      ],
      dialogTitle: null,
      dialogFormVisible: false,
      dialogFormPicVisible: false,
      materialNameLike: "", // 品种名称模糊查询
      // 单位选择列表
      unitlist: [],
      unitlists: [], // 体积单位
      // 农资选择列表
      agrSourseTypeList: [],
      // 已选择的农资列表
      selectnozilist: [],
      agriculturalMaterialTypeName: "",
      // 新增的规则校验
      isshowmessage: false,
      rules: {
        batchNo: [
          {
            required: true,
            message: "请选择批次",
            trigger: ["change", "blur"],
          },
        ],
        facilityNoList: [
          {
            required: true,
            message: "请选择设施",
            trigger: ["change", "blur"],
          },
        ],
        materialNo: [
          { required: true, message: "请选择农资名称", trigger: "change" },
        ],
        personNo: [
          {
            required: true,
            message: "请选择经手人",
            trigger: ["change", "blur"],
          },
        ],
        assetQuantity: [
          { required: true, message: "请输入投入量", trigger: "blur" },
        ],
        // unitNo: [{ required: true, message: "请选择单位", trigger: "change" }],
        assetDate: [
          { required: true, message: "请选择投入日期", trigger: "change" },
        ],
      },
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      // 农资图片
      imgUrl: "",
      // 搜索提交
      searchlist: {},
      batchNo: "",
      facilityNo: "",
      materialNo: "",
      // 批次
      batchList: [],
      batchAList: [],
      // 设施
      facilityList: [],
      facilityAList: [],
      formData: {
        facilityNoList: "",
        batchNo: "",
        personNo: "",
        assetQuantity: "",
        unitNo: "",
        // loss: '',
        assetValue: "",
        assetDate: "",
        remark: "",
        pictureNo: "",
        batchSingleNos: [],
        materialNo: "",
        exchangeUnitNo: "",
        exchangeRatio: "",
        assetQuantity: "",
      },
      // 农资名称
      agriculturalMaterialList: [],
      queryagriculturalMaterialList: [],
      // 员工
      // 图片上传
      basicUrl: `${baseURL.webServiceUrl}v3/inputs/picture/`,
      // 重置
      reseUrl: `${baseURL.webServiceUrl}v3/inputs/picture/`,
      image: "",
      fileList: [],
      // 部门岗位员工列表
      departmentList: [],
      postList: [],
      staffList: [],
      personNo: "",
      facilityBOList: [],
      isShowEquip: false,
      activeSingleNoList: [],
    };
  },
  computed: {
    headers() {
      return {
        accessToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        sysDataBaseName: sessionStorage.databaseName,
      };
    },
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    nowChanceStau(newval) {
      if (newval === "add") {
        this.isshowmessage = true;
        this.selectnozilist = [];
        this.agriculturalMaterialTypeName = "";
      } else if (newval === "edit") {
        this.isshowmessage = true;
      } else if (newval === "") {
        this.isshowmessage = false;
      }
    },
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs.formData.clearValidate();
        });
      }
    },
  },
  mounted() {
    this.getselectmessage();
    this.getTableDataList();
    this.tableData = [];
  },
  methods: {
    // 查看编号
    async seeIdNameList(row) {
      this.showIdNameList = true;
      let res = await managementtwo.getNOList(row.batchNo);
      this.singleNoList = res.data.singleNoList;
      this.activeSingleNoList = row.batchSingleNos;
    },
    seeEquip(row) {
      console.log("a");
      this.facilityBOList = row.facilityBOList;
      this.isShowEquip = true;
      console.log(this.isShowEquip);
      console.log(row.facilityBOList);
    },
    // 选择设施
    async changeFacilityNo(e) {
      this.batchAList = [];
      this.formData.batchNo = "";
      this.$set(this.formData, "batchSingleNos", []);
      this.singleNoList = [];
      let params = {
        facilityNo: e,
        batchType: "SINGLE",
      };
      let res = await batcjreq.accordPlotGetBatchs(params);
      this.batchAList = res.data;
    },
    // 选择批次
    async getspecification(e) {
      // 获取编号
      this.$set(this.formData, "batchSingleNos", []);
      this.singleNoList = [];
      if (e) {
        let res = await managementtwo.getNOList(e);
        this.singleNoList = res.data.singleNoList;
      }
    },
    materialNoChange() {
      let index = this.agriculturalMaterialList.findIndex((el) => {
        return this.formData.materialNo === el.materialNo;
      });
      let obj = this.agriculturalMaterialList[index];
      this.$set(
        this.formData,
        "spec",
        obj.specification
          ? obj.specification + obj.perSpecUnitName + "/" + obj.unitName
          : ""
      );
    },
    // 导出
    async download() {
      let params = {
        entity: {
          ...this.entity,
        },
      };
      let url = "v3/inputs/inputsRecord/download";
      let excel = "农资投入表";
      this.downloadExcel(url, params, excel);
    },
    // 获取当前表格信息
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchNo: this.searchlist.batchNo || undefined,
          facilityNo: this.searchlist.facilityNo || undefined,
          startTime:
            this.searchlist.date &&
            this.dateToFormattwo(this.searchlist.date[0]),
          endTime:
            this.searchlist.date &&
            this.dateToFormattwo(this.searchlist.date[1]),
          personNo: this.searchlist.personNo || undefined,
          materialNo: this.searchlist.materialNo || undefined,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          organizationNo: sessionStorage.organizationNo,
          batchType: "SINGLE",
        },
      };
      this.entity = params.entity;
      managementtwo.getTableDataList(params).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前农业类型表格获取失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.tableData.forEach((el) => {
          el["viewImg"] = false;
        });
        // console.log(this.tableData)
        this.addblankmet();
        this.resetActionBar();
      });
    },
    // 获取下拉数据
    getselectmessage() {
      // this.getDepartmentList();
      // 获取单位选择框数据
      danwei
        .getallBasicunitlist({ unitTypeNo: "1001491616960118784" })
        .then((res) => {
          this.unitlist = res.data;
        });
      nowstaff.getStaffListByCondition().then((res) => {
        this.staffList = res.data;
        this.formConfig[3].options = res.data.map((el) => {
          return { ...el, personName: el.person?.name };
        });
      });
      danwei
        .getallunitlist({
          unitTypeNo: "995416607651037184",
          organizationNo: sessionStorage.organizationNo,
        })
        .then((res) => {
          this.unitlists = res.data;
        });
      // 获取批次选择框数据
      let param = {};
      if (this.nowChanceStau === "add") {
        param = {
          farmingTypeNo: sessionStorage.farmingTypeNo,
          status: false,
          batchType: "SINGLE",
          simpleData: true
        };
      } else {
        param = {
          farmingTypeNo: sessionStorage.farmingTypeNo,
          batchType: "SINGLE",
          simpleData: true
        };
      }
      managementtwo.queryBatchList(param).then((res) => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      let params = {};
      if (this.nowChanceStau === "add") {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        };
      } else {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",")
            .concat([sessionStorage.parentId || ""]),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        };
      }
      // 获取设施选择框数据 queryFacilityListName
      userreq.getfacilityAll(params).then((res) => {
        this.facilityList = res.data;
        this.facilityAList = res.data;
        this.formConfig[1].options = res.data;
      });
      managementtwo.getqueryList().then((res) => {
        this.queryagriculturalMaterialList = res.data;
        this.formConfig[2].options = res.data;
      });
      // 获取农资下拉内容
      nowpagereq.getqueryList("").then((res) => {
        let data = res.data;
        // 赋值总条数
        // this.totalSize = data.totalElements;
        // 赋值数组
        this.agriculturalMaterialList = data;
      });
    },
    // 农资数据处理掉空child
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      newArr = arr.map((item) => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child),
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter((item) => item != null);
      return newArr;
    },
    cascaderChange(e) {
      // console.log(e);
    },
    // 查询当前图片
    upimage(e, index) {
      this.tableData.forEach((el) => {
        el["viewImg"] = false;
      });
      this.$set(this.tableData[index], "viewImg", true);
      if (e) {
        this.imgUrl = "";
        this.dialogFormPicVisible = true;
        managementtwo.getimage(e).then((res) => {
          let data = res.data || {};
          this.imgUrl = `data:image/png;base64,${data.pictureData}`;
        });
      }
    },
    // 上传图片
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${this.basicUrl}add`;
        // console.log(URL)
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    handleResponse(response, file, fileList) {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        this.pictureNo = response.data;
        collectionPicture.getColectPicture(this.pictureNo).then((res) => {
          this.image = "data:image/png;base64," + res.data.pictureData;
        });
        return this.image;
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    handleRemove() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        // console.log(response);
        collectionPicture.delCollectionPicture(this.pictureNo).then((res) => {
          if (res.code === 1) {
            delete this.pictureNo;
            delete this.formData.pictureNo;
            // console.log(this.formData)
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    dateFormat(row, colnum) {
      if (row.inputsRecordNo) {
        // console.log(row)
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD MM:SS:mm");
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    add() {
      this.openDialog("add");
      this.formData = {};
      this.batchAList = [];
      this.singleNoList = [];
      this.formData.batchNo = "";
      this.$nextTick(() => {
        this.formData = { ...this.formData };
        this.$refs.formData.resetFields();
      });
    },
    // 修改
    async handleEdit(list) {
      console.log(list);
      let res = await managementtwo.getNOList(list.batchNo);
      this.singleNoList = res.data.singleNoList;
      this.formData = JSON.parse(JSON.stringify(list));
      // 获取批次选择框数据
      // this.formData.batchNo = list.batchVO.batchNo;
      // this.formData.materialNo = list.agriculturalMaterialDTO.materialNo;
      // managementtwo.queryBatchListName().then((res) => {
      //   this.batchList = res.data;
      //   this.formConfig[0].options = res.data;
      // });
      let facilitList = [];
      if (list.facilityBOList) {
        list.facilityBOList.forEach((item) => {
          // console.log(item.facilityNo)
          if (item.facilityNo) {
            let list = this.$set(item, "facilityNo", item.facilityNo);
            facilitList = list;
          }
        });
      }
      this.batchAList = [list.productionBatchBO];
      this.getStaffList();
      this.formData = {
        facilityNoLists: [list],
        facilityNoList: facilitList,
        batchNo: list.productionBatchBO.batchName,
        batchNos: list.batchNo,
        materialNo: list.materialNo,
        personNo: list.personNo,
        assetQuantity: list.assetQuantity,
        unitNo: list.unitNo,
        // loss: list.loss,
        assetValue: list.assetValue,
        assetDate: list.assetDate,
        remark: list.remark,
        pictureNo: list.pictureNo,
        exchangeUnitNo: list.exchangeUnitNo,
        exchangeRatio: list.exchangeRatio,
        // agriculturalMaterialDTO: list.agriculturalMaterialDTO,
        // agriculturalMaterialInputId: list.agriculturalMaterialInputId,
        productionBatchBO: list.productionBatchBO,
        facilityVOList: list.facilityVOList,
        farmingTypeNo: list.farmingTypeNo,
        handlerName: list.handlerName,
        organizationNo: list.organizationNo,
        unitName: list.unitName,
        inputsRecordNo: list.inputsRecordNo,
        remark: list.remark,
        spec: `${list.materialDTO.specification}${list.materialDTO.perSpecUnitName}/${list.materialDTO.unitName}`,
      };
      this.$set(this.formData, "batchSingleNos", list.batchSingleNos);
      this.openDialog("edit");
      if (this.formData.pictureNo) {
        // return this.basicUrl + query/ + this.pictureNo
        this.pictureNo = this.formData.pictureNo;
        collectionPicture.getColectPicture(this.pictureNo).then((res) => {
          this.image = "data:image/png;base64," + res.data.pictureData;
        });
      } else {
        this.image = "";
      }
    },
    handleSelectionChange(list) {
      this.agriculturalMaterialInputIdList = [];
      this.agriculturalMaterialInputIdList = list.map((item) => {
        return item.inputsRecordNo;
      });
      if (
        this.agriculturalMaterialInputIdList &&
        this.agriculturalMaterialInputIdList.length > 0
      ) {
        this.delActive = true;
      } else this.delActive = false;
    },
    delmessage() {
      if (this.nowChanceStau === "del") {
        let params = {
          noList: this.agriculturalMaterialInputIdList,
        };
        managementtwo.delmeslist(params).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    handleDelete(data) {
      // managementtwo.delmeslist(params).then(res => {
      //   if (res.code === 1) {
      //     this.getTableDataList();
      //     this.$message.success("删除成功");
      //   } else {
      //     this.$message.error("删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: [data.inputsRecordNo],
          };
          managementtwo.delmeslist(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            this.formData.pictureNo = this.pictureNo;
            let parone = {
              ...this.formData,
            };
            this.batchList.forEach((item) => {
              if (item.batchId === parone.batchId) {
                parone.organizationId =
                  item.organizationId || "批次暂无组织结构id";
              }
            });
            parone.batchNo = this.formData.batchNo;
            parone.facilityNoList = [this.formData.facilityNoList];
            managementtwo.addmeslist(parone).then((res) => {
              if (res.code === 1) {
                this.closeDialog();
                this.getTableDataList();
                this.$message.success("添加成功");
                this.image = "";
                this.pictureNo = ''
              } else {
                this.$message.error("添加失败");
              }
            });
            // 修改
          } else if (this.nowChanceStau === "edit") {
            this.formData.pictureNo = this.pictureNo;
            let params = { ...this.formData };
            params.batchNo = params.batchNos;
            params.facilityNoList = [
              params.facilityNoLists[0].facilityBOList[0].facilityNo,
            ];
            delete params["batchNos"];
            delete params["facilityNoLists"];
            delete params["agriculturalMaterialType"];
            if (this.selectnozilist === []) {
              //   console.log("")
            } else {
              delete params["agriculturalMaterialTypeName"];
              params["agriculturalMaterialTypeId"] =
                this.selectnozilist[this.selectnozilist.length - 1];
            }
            // console.log("单个修改", params);return
            managementtwo.editmeslist(params).then((res) => {
              if (res.code === 1) {
                this.closeDialog();
                this.getTableDataList();
                this.$message.success("修改成功");
                this.image = "";
                this.pictureNo = ''
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          this.$message.warning("请填写完整！！！");
        }
      });

      // this.confirmUploadFile(()=>{

      //   this.$refs["formData"].validate((valid) => {
      //     if (valid) {
      //       if (this.nowChanceStau === "add") {
      //         // this.formData.multipartFile = this.fileList;
      //         let parone = {
      //           ...this.formData
      //         };
      //         this.batchList.forEach(item => {
      //           if (item.batchNo === parone.batchNo) {
      //             parone.organizationNo = item.organizationNo || "批次暂无组织结构id";
      //           }
      //         });
      //         managementtwo.addmeslist(parone).then(res => {
      //           if (res.code === 1) {
      //             // 上传文档
      //             this.getTableDataList();
      //             this.$message.success("添加成功");
      //             this.closeDialog();
      //             this.image = "";
      //           } else {
      //             this.$message.error("添加失败");
      //           }
      //         });
      //       }
      //       if (this.nowChanceStau === "edit") {
      //         this.formData.pictureNo = this.pictureNo;
      //         let params = this.formData;
      //         delete params["agriculturalMaterialType"];
      //         if (this.selectnozilist === []) {
      //           //   console.log("")
      //         } else {
      //           delete params["agriculturalMaterialTypeName"];
      //           params["agriculturalMaterialTypeId"] = this.selectnozilist[
      //             this.selectnozilist.length - 1
      //           ];
      //         }
      //         managementtwo.editmeslist(params).then(res => {
      //           if (res.code === 1) {
      //             this.getTableDataList();
      //             this.$message.success("修改成功");
      //             this.closeDialog();
      //             this.image = "";
      //           } else {
      //             this.$message.error("修改失败");
      //           }
      //         });
      //       }
      //     } else {
      //       this.$message.warning("请填写完整！！！")
      //     }
      //   })
      // })
    },
    cancel() {
      this.image = "";
      this.formData = {};
      this.$set(this.formData,'pictureNo','')
      this.pictureNo = ''
      this.closeDialog();
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    numChange(field) {
      this.formData[field] < 0 && (this.formData[field] = 0);
    },
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then((res) => {
        if (res.code !== 1) {
          return;
        }
        this.staffList = res.data;
      });
    },

    handleChangeFile(file, fileList) {
      this.fileList.push(file);
    },
    handleRemoveFile(file, fileList) {
      let index = this.fileList.findIndex((el) => el.name === file.name);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },
    confirmUploadFile(cb) {
      let params = {
        // inputsRecordNo: inputsRecordNo,
        multipartFile: this.fileList[0].raw,
      };
      managementtwo.uploadImage(params).then((res) => {
        if (res.code !== 1) {
          return;
        }
        cb(res);
      });
    },
    closeViewImg() {
      this.tableData.forEach((el) => {
        el["viewImg"] = false;
      });
      this.$set(this, "tableData", this.tableData);
      this.itemKey = Math.random()
      this.dialogFormPicVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.tabhid {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  // background-color: #0cb28c;
}
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
::v-deep .staff-manage .common-layout .content {
  overflow-y: auto;
}
.upimg {
  ::v-deep .xunzeimage {
    width: 140px !important;
  }
}
.dialog {
  img {
    width: auto;
    max-width: 100%;
  }
}
::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}
::v-deep .el-upload--picture-card {
  position: relative;
}
::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
::v-deep .el-dialog__body {
  height: 90%;
  text-align: center;
  // img {
  //   width: 100%;
  // }
}
::v-deep .el-upload__tip {
  display: none;
}
// 查看编号
.IdNameList {
  height: 33px;
  margin-right: 10px;
  padding: 0 5px;
  margin-bottom: 5px;
  color: #000;
  text-align: center;
  line-height: 33px;
  border: 1px solid #006e91;
}
.activeId {
  background-color: #006e91;
  color: #fff;
}
.viewImgContainer {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .viewImg {
    width: 80px;
    height: 32px;
    cursor: pointer;
    background: url("~@/assets/unifiedPicture/viewImg-d.png") no-repeat 100%
      100%;
    &:hover {
      background: url("~@/assets/unifiedPicture/viewImg.png") no-repeat 100%
        100%;
    }
  }
}
</style>
